package com.example.usermanager.config;

import com.example.usermanager.util.ConstVariable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author 郝文雪
 * @date 2022/8/6 10:03
 * @Description 自定义用户拦截器
 */
@Component
public class LoginIntercept implements HandlerInterceptor {
    /**
     * true表示用户已经登录，会继续访问目标方法
     * false表示未登录，跳转到登录页面
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session=request.getSession(false);
        if(session!=null && session.getAttribute(ConstVariable.USER_SESSION_KEY)!=null){
            //表示已经登录
            return true;
        }
        //执行到此行表示未登录，跳转到登录页面
        response.sendRedirect("/login.html");
        return false;
    }
}
